﻿/* $RCSFile: CrmHelper.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/CrmHelper.cs $
 * $log$
 * Revision 19 2010/10/02 14:49:04  christian.surieux
 *   Updated ADNDynImage for PimaryFieldStringValue, added name override and changed Telerik version
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using CrmSdk;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;


namespace AddonNice.Helpers
{
    public class CrmHelper
    {
        /// <summary>
        /// Return the static Wrapper stored in PortalSecurity
        /// </summary>
        static public CRMWrapperBase Wrapper
        {
            get
            {
                return AddonNice.Security.PortalSecurity.Wrapper;
            }
        }

        /// <summary>
        /// install a recent wrapper in dynEntity
        /// </summary>
        static public void ResetWrapper(DynEntity dyn)
        {
            dyn.SetWrapper(AddonNice.Security.PortalSecurity.Wrapper);
        }

        static public void BuildSysUserList(BaseDataType sender,EventArgs ev)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper BuildSysUserList BEG.", CRMTraceSwitch.Sw.Info);
            Guid firstOwner                     =   Guid.Empty;
            ArrayList arOw                      =   BuildSysUserList0(ref firstOwner);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSysUserList SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   firstOwner.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSysUserList init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(arOw,SelVal);
        }
        
        static public ArrayList BuildSysUserList0(ref Guid firstOwner)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper BuildSysUserList0 BEG.", CRMTraceSwitch.Sw.Info);
            firstOwner                              =   Guid.Empty;
            ArrayList arOw                          =   null;
            const string key                        =   "PotentialSysUserList";
            if (Cache2.Exists(key))
            {
                arOw                                =   (ArrayList)Cache2.Get(key);
                firstOwner                          =   ((CrmListItem)arOw[0]).ID;
            }
            else 
            {
                arOw                                =   Wrapper.Util.PotentialOwners(ref firstOwner,false);
                if ( arOw.Count > 0 )
                    Cache2.Insert(key,arOw);
            }
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSysUserList0 END count: {0}, firstOwner: {1}.", arOw.Count,firstOwner), CRMTraceSwitch.Sw.Info);
            return arOw;
        }

        static public void BuildAccountList(BaseDataType sender,EventArgs ev)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper BuildAccountList BEG.", CRMTraceSwitch.Sw.Info);
            Guid firstOwner                     =   Guid.Empty;
            ArrayList arOw                      =   BuildAccountList0(ref firstOwner);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   firstOwner.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(arOw,SelVal);
        }
        /// <summary>
        /// Idem but with  insert the None option which means don't force in this module
        /// </summary>
        static public void BuildAccountList1(BaseDataType sender,EventArgs ev)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper BuildAccountList BEG.", CRMTraceSwitch.Sw.Info);
            Guid firstOwner                     =   Guid.Empty;
            ArrayList arOw                      =   BuildAccountList0(ref firstOwner);
            // insert the None option which means don't force in this module
            CrmListItem t                       =   new CrmListItem("None", Guid.Empty);
            arOw.Insert(0,t);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(arOw,SelVal);
        }

        static public ArrayList BuildAccountList0(ref Guid firstOwner)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper BuildAccountList0 BEG.", CRMTraceSwitch.Sw.Info);
            firstOwner                              =   Guid.Empty;
            ArrayList arOw                          =   null;
            const string key                        =   "PotentialAccountList";
            if (Cache2.Exists(key))
            {
                arOw                                =   (ArrayList)Cache2.Get(key);
                firstOwner                          =   ((CrmListItem)arOw[0]).ID;
            }
            else 
            {
                InternalConditionExpression c1      =   new InternalConditionExpression();
                c1.AttributeName                    =   CrmStr.statecode;
                c1.Operator                         =   InternalConditionOperator.Equal;
                c1.Values                           =   new object[]{CrmStr.StateActive};
                arOw                                =   Wrapper.Util.PotentialEntities(CrmStr.account,c1,ref firstOwner,false);
                if ( arOw.Count > 0 )
                    Cache2.Insert(key,arOw);
            }
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList0 END count: {0}, firstOwner: {1}.", arOw.Count,firstOwner), CRMTraceSwitch.Sw.Info);
            return arOw;
        }
        
        static public ArrayList FirstAccount(ref Guid firstOwner)
        {
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmHelper FirstAccount BEG.", CRMTraceSwitch.Sw.Info);
            firstOwner                          =   Guid.Empty;
            ArrayList arOw                      =   null;
            InternalConditionExpression c1      =   new InternalConditionExpression();
            c1.AttributeName                    =   CrmStr.statecode;
            c1.Operator                         =   InternalConditionOperator.Equal;
            c1.Values                           =   new object[]{CrmStr.StateActive};
            arOw                                =   Wrapper.Util.PotentialEntities(CrmStr.account,c1,ref firstOwner,true);
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountList0 END count: {0}, firstOwner: {1}.", arOw.Count,firstOwner), CRMTraceSwitch.Sw.Info);
            return arOw;
        }

        static public void BuildAccountQueryTable(BaseDataType sender,EventArgs ev)
        {
            DataTable TbQueries                 =   Wrapper.Util.BuildUserQueryTable(CrmStr.account,new ResetWrapperHandler(ResetWrapper));
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountQueryTable count: {0}.", (TbQueries == null) ? 0:TbQueries.Rows.Count), CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountQueryTable SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountQueryTable init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(TbQueries,SelVal);
        }

        static public void BuildQueryTable(BaseDataType sender,EventArgs ev)
        {
            string entityName                   =   CrmStr.account;
            if ( sender.HasCrmEntity )
                entityName                      =   sender.CrmEntity;
            DataTable TbQueries                 =   Wrapper.Util.BuildUserQueryTable(entityName,new ResetWrapperHandler(ResetWrapper));
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildQueryTable count: {0}.", (TbQueries == null) ? 0:TbQueries.Rows.Count), CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildQueryTable SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildQueryTable init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(TbQueries,SelVal);
        }

        static public void BuildAccountSavedQueryTable(BaseDataType sender,EventArgs ev)
        {
            DataTable TbQueries                 =   Wrapper.Util.BuildSavedQueryTable(CrmStr.account,new ResetWrapperHandler(ResetWrapper));
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountSavedQueryTable count: {0}.", (TbQueries == null) ? 0:TbQueries.Rows.Count), CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountSavedQueryTable SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildAccountSavedQueryTable init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(TbQueries,SelVal);
        }

        static public void BuildSavedQueryTable(BaseDataType sender,EventArgs ev)
        {
            string entityName                   =   CrmStr.account;
            if ( sender.HasCrmEntity )
                entityName                      =   sender.CrmEntity;
            DataTable TbQueries                 =   Wrapper.Util.BuildSavedQueryTable(entityName,new ResetWrapperHandler(ResetWrapper));
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSavedQueryTable count: {0}.", (TbQueries == null) ? 0:TbQueries.Rows.Count), CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSavedQueryTable SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper BuildSavedQueryTable init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(TbQueries,SelVal);
        }

        #region currency


        /// <summary>
        /// Get  a currency from its 3 letter iso symbol
        /// </summary>
        static public ADNDynTransactionCurrency GetTransactionCurrencyBy3letters(string CSymbol)
        {
            Guid SelectedGuid   =   Guid.Empty;
            SortedList<string,ADNDynTransactionCurrency> lst    =   GetTransactionCurrencies0(ref SelectedGuid);
            foreach (ADNDynTransactionCurrency dynC in lst.Values )
                if ( dynC.isocurrencycode == CSymbol )
                {
                    if ( CRMTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencyBy3letters found {0}.",dynC.name),CRMTraceSwitch.Sw.Info);
                    return dynC;
                }
            if ( CRMTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmHelper GetTransactionCurrencyBy3letters NOT found {0}.",CSymbol),CRMTraceSwitch.Sw.Info);
            return null;
        }
        

        /// <summary>
        /// Static method called before a settingItem needs to bind
        /// Read all available currencies in this Crm
        /// </summary>
        static public void GetTransactionCurrencies(BaseDataType sender,EventArgs ev)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmHelper GetTransactionCurrencies BEG.",CRMTraceSwitch.Sw.Info);
            Guid SelectedGuid                                           =   Guid.Empty;
            SortedList<string,ADNDynTransactionCurrency> currencyList   =   GetTransactionCurrencies0(ref SelectedGuid);
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencies found Count: {0}",currencyList.Count),CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal               =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencies SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal) && (currencyList.Count > 0 ))
            {
                SelVal                          =   SelectedGuid.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencies init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            if ( ev is CurrencyEventArg )
                ((CurrencyEventArg)ev).CPChooser.CurrencyList   =   currencyList;
            else if ( sender is ListDataType )
                ((ListDataType)sender).ResetDataSource(currencyList.Values,SelVal);            
        }

        /// <summary>
        /// Get from Crm all available TransactionCurrency with statecode active
        /// </summary>
        static public SortedList<string,ADNDynTransactionCurrency> GetTransactionCurrencies0(ref Guid SelectedGuid)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmHelper ADNDynTransactionCurrency0 BEG.",CRMTraceSwitch.Sw.Info);
            const string TransactionCurrencyKey             =   "TransactionCurrencyKey";
            SortedList<string,ADNDynTransactionCurrency> TransactionCurrencyList    =   null;
            if (AddonNice.Settings.Cache.CurrentCache.Exists(TransactionCurrencyKey))
            {
                TransactionCurrencyList                     =   (SortedList<string,ADNDynTransactionCurrency>)AddonNice.Settings.Cache.CurrentCache.Get(TransactionCurrencyKey);
                if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencies0 found in cache Count: {0}",TransactionCurrencyList.Count),CRMTraceSwitch.Sw.Info);
            }
            else
            {
                InternalQueryExpression qe                  =   new InternalQueryExpression();
                qe.EntityName                               =   CrmStr.transactioncurrency;
                InternalColumnSet RequestCols               =   new InternalColumnSet();
                RequestCols.Attributes                      =   new string[]
                                                                {
                                                                    CrmStr.currencyname,
                                                                    CrmStr.transactioncurrencyid,
                                                                    CrmStr.currencysymbol,
                                                                    CrmStr.isocurrencycode,
                                                                    CrmStr.exchangerate
                                                                };
                qe.ColumnSet                                =   RequestCols;
                InternalFilterExpression fi                 =   new InternalFilterExpression();
                InternalConditionExpression ex3             =   new InternalConditionExpression();
                ex3.AttributeName                           =   CrmStr.statecode;
                ex3.Operator                                =   InternalConditionOperator.Equal;
                ex3.Values                                  =   new object[]{CrmStr.StateActive};
                fi.FilterOperator                           =   InternalLogicalOperator.And;
                fi.Conditions                               =   new InternalConditionExpression[]{ex3};
                qe.Criteria                                 =   fi;
                try
                {
                    TransactionCurrencyList                 =   Wrapper.Util.FindEntitiesByQuery<ADNDynTransactionCurrency>(qe,new ResetWrapperHandler(ResetWrapper), ref SelectedGuid);
                    if ( TransactionCurrencyList.Count > 0 )
                        AddonNice.Settings.Cache.CurrentCache.Insert(TransactionCurrencyKey,TransactionCurrencyList);
                }
                catch (Exception exp)
                {
                    if (CRMTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmHelper GetTransactionCurrencies0 ex: {0}", exp), CRMTraceSwitch.Sw.Info);
                    throw;
                }
            }
            if ( TransactionCurrencyList.Count > 0 )
                SelectedGuid                                =   TransactionCurrencyList.Values[0].transactioncurrencyid;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetTransactionCurrencies0 found Count: {0}, SelectedGuid: {1}",TransactionCurrencyList.Count,SelectedGuid),CRMTraceSwitch.Sw.Info);
            return TransactionCurrencyList;            
        }

        #endregion Currency

        #region PriceList

        /// <summary>
        /// Static method called before a settingItem needs to bind
        /// </summary>
        static public void GetPriceLists(BaseDataType sender,EventArgs ev)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmHelper GetPriceLists BEG.",CRMTraceSwitch.Sw.Info);
            Guid SelectedGuid                               =   Guid.Empty;
            SortedList<string,ADNDynPricelevel> priceList    =   GetPriceLists0(ref SelectedGuid);
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists found Count: {0}",priceList.Count),CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal               =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal) && (priceList.Count > 0 ))
            {
                SelVal                          =   SelectedGuid.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(priceList.Values,SelVal);            
        }

        /// <summary>
        /// Idem GetPriceLists but with an empty price list added in first pos and selected if no existing selection
        /// </summary>
        static public void GetPriceLists1(BaseDataType sender,EventArgs ev)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmHelper GetPriceLists1 BEG.",CRMTraceSwitch.Sw.Info);
            Guid SelectedGuid                   =   Guid.Empty;
            SortedList<string,ADNDynPricelevel> priceList    =   GetPriceLists0(ref SelectedGuid);
            // We must make a copy before adding new element
            priceList                           =   new SortedList<string,ADNDynPricelevel>(priceList);
            // Add the Empty item
            ADNDynPricelevel EmptPl             =   new ADNDynPricelevel(new ResetWrapperHandler(ResetWrapper),Guid.Empty);
            EmptPl.name                         =   "No selection";
            EmptPl.description                  =   "No selection";
            EmptPl.pricelevelid                 =   Guid.Empty;
            EmptPl.begindate                    =   CRMUtil.minDateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
            EmptPl.enddate                      =   CRMUtil.maxDateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
            EmptPl.PropertyDescriptorCollection =   (priceList.Count > 0 ) ? priceList.Values[0].PropertyDescriptorCollection: null;
            priceList.Add(" ",EmptPl);
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists1 found Count: {0}",priceList.Count),CRMTraceSwitch.Sw.Info);
            // Install datasource and preserve actual selected value if here
            string SelVal                       =   sender.Val;
            if (CRMTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists1 SelVal: '{0}'.",SelVal), CRMTraceSwitch.Sw.Info);
            if (string.IsNullOrEmpty(SelVal) && (priceList.Count > 0 ))
            {
                SelVal                          =   Guid.Empty.ToString();
                if (CRMTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists1 init on First SelVal: '{0}'.", SelVal), CRMTraceSwitch.Sw.Info);
            }
            ((ListDataType)sender).ResetDataSource(priceList.Values,SelVal);            
        }

        /// <summary>
        /// Get from Crm all available Pricelist with stardate and endate Ok for today
        /// also check the statecode active
        /// </summary>
        static public SortedList<string,ADNDynPricelevel> GetPriceLists0(ref Guid SelectedGuid)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmHelper GetPriceLists0 BEG.",CRMTraceSwitch.Sw.Info);
            const string PriceListKey                       =   "PriceListKey";
            SortedList<string,ADNDynPricelevel> priceList    =   null;
            if (AddonNice.Settings.Cache.CurrentCache.Exists(PriceListKey))
            {
                priceList                                   =   (SortedList<string,ADNDynPricelevel>)AddonNice.Settings.Cache.CurrentCache.Get(PriceListKey);
                if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists0 found in cache Count: {0}",priceList.Count),CRMTraceSwitch.Sw.Info);
            }
            else
            {
                InternalQueryExpression qe                  =   new InternalQueryExpression();
                qe.EntityName                               =   CrmStr.pricelevel;
                InternalColumnSet RequestCols               =   new InternalColumnSet();
                RequestCols.Attributes                      =   new string[]
                                                                {
                                                                    CrmStr.name,
                                                                    CrmStr.pricelevelid,
                                                                    CrmStr.begindate,
                                                                    CrmStr.enddate,
                                                                    CrmStr.description,
                                                                    CrmStr.transactioncurrencyid, // added 30/4/09
                                                                    CrmStr.freighttermscode,
                                                                    CrmStr.shippingmethodcode
                                                                };
                qe.ColumnSet                                =   RequestCols;
                InternalFilterExpression fi                 =   new InternalFilterExpression();
                string curDate                              =   string.Format(CultureInfo.InvariantCulture, "{0:s}", DateTime.Now);
                InternalConditionExpression ex              =   new InternalConditionExpression();
                ex.AttributeName                            =   CrmStr.begindate;
                ex.Operator                                 =   InternalConditionOperator.OnOrBefore;
                ex.Values                                   =   new object[]{curDate};
                InternalConditionExpression ex2             =   new InternalConditionExpression();
                ex2.AttributeName                           =   CrmStr.enddate;
                ex2.Operator                                =   InternalConditionOperator.OnOrAfter;
                ex2.Values                                  =   new object[]{curDate};
                InternalConditionExpression ex3             =   new InternalConditionExpression();
                ex3.AttributeName                           =   CrmStr.statecode;
                ex3.Operator                                =   InternalConditionOperator.Equal;
                ex3.Values                                  =   new object[]{CrmStr.StateActive};
                fi.FilterOperator                           =   InternalLogicalOperator.And;
                fi.Conditions                               =   new InternalConditionExpression[]{ex,ex2,ex3};
                qe.Criteria                                 =   fi;
                try
                {
                    priceList                               =   Wrapper.Util.FindEntitiesByQuery<ADNDynPricelevel>(qe,new ResetWrapperHandler(ResetWrapper), ref SelectedGuid);
                    if ( priceList.Count > 0 )
                        AddonNice.Settings.Cache.CurrentCache.Insert(PriceListKey,priceList);
                }
                catch (Exception exp)
                {
                    if (CRMTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmHelper GetPriceLists0 ex: {0}", exp), CRMTraceSwitch.Sw.Info);
                    throw;
                }
            }
            if ( priceList.Count > 0 )
                SelectedGuid                                =   priceList.Values[0].pricelevelid;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceLists0 found Count: {0}, SelectedGuid: {1}",priceList.Count,SelectedGuid),CRMTraceSwitch.Sw.Info);
            return priceList;            
        }

        /// <summary>
        /// Get from Crm all available Pricelist with stardate and endate Ok for today
        /// also check the statecode active
        /// </summary>
        static public SortedList<string,ADNDynPricelevel> GetPriceListsByCurrency(Guid CurrencyId,ref Guid SelectedGuid)
        {
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceListsByCurrency BEG CurrencyId: {0}.",CurrencyId),CRMTraceSwitch.Sw.Info);
            string PriceListKey                             =   string.Format("PriceListByCurrencyKey_{0}",CurrencyId);
            SortedList<string,ADNDynPricelevel> priceList    =   null;
            if (AddonNice.Settings.Cache.CurrentCache.Exists(PriceListKey))
            {
                priceList                                   =   (SortedList<string,ADNDynPricelevel>)AddonNice.Settings.Cache.CurrentCache.Get(PriceListKey);
                if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceListsByCurrency found in cache Count: {0}",priceList.Count),CRMTraceSwitch.Sw.Info);
            }
            else
            {
                InternalQueryExpression qe                  =   new InternalQueryExpression();
                qe.EntityName                               =   CrmStr.pricelevel;
                InternalColumnSet RequestCols               =   new InternalColumnSet();
                RequestCols.Attributes                      =   new string[]
                                                                {
                                                                    CrmStr.name,
                                                                    CrmStr.pricelevelid,
                                                                    CrmStr.begindate,
                                                                    CrmStr.enddate,
                                                                    CrmStr.description,
                                                                    CrmStr.transactioncurrencyid, // added 30/4/09
                                                                    CrmStr.freighttermscode,
                                                                    CrmStr.shippingmethodcode
                                                                };
                qe.ColumnSet                                =   RequestCols;
                InternalFilterExpression fi                 =   new InternalFilterExpression();
                string curDate                              =   string.Format(CultureInfo.InvariantCulture, "{0:s}", DateTime.Now);
                InternalConditionExpression ex              =   new InternalConditionExpression();
                ex.AttributeName                            =   CrmStr.begindate;
                ex.Operator                                 =   InternalConditionOperator.OnOrBefore;
                ex.Values                                   =   new object[]{curDate};
                InternalConditionExpression ex2             =   new InternalConditionExpression();
                ex2.AttributeName                           =   CrmStr.enddate;
                ex2.Operator                                =   InternalConditionOperator.OnOrAfter;
                ex2.Values                                  =   new object[]{curDate};
                
                InternalConditionExpression ex2a             =   new InternalConditionExpression();
                ex2a.AttributeName                           =   CrmStr.transactioncurrencyid;
                ex2a.Operator                                =   InternalConditionOperator.Equal;
                ex2a.Values                                  =   new object[]{CurrencyId};

                InternalConditionExpression ex3             =   new InternalConditionExpression();
                ex3.AttributeName                           =   CrmStr.statecode;
                ex3.Operator                                =   InternalConditionOperator.Equal;
                ex3.Values                                  =   new object[]{CrmStr.StateActive};
                
                fi.FilterOperator                           =   InternalLogicalOperator.And;
                fi.Conditions                               =   new InternalConditionExpression[]{ex2a,ex,ex2,ex3};
                qe.Criteria                                 =   fi;
                try
                {
                    priceList                               =   Wrapper.Util.FindEntitiesByQuery<ADNDynPricelevel>(qe,new ResetWrapperHandler(ResetWrapper),ref SelectedGuid);
                    if ( priceList.Count > 0 )
                        AddonNice.Settings.Cache.CurrentCache.Insert(PriceListKey,priceList);
                }
                catch (Exception exp)
                {
                    if (CRMTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmHelper GetPriceListsByCurrency ex: {0}", exp), CRMTraceSwitch.Sw.Info);
                    throw;
                }
            }
            if ( priceList.Count > 0 )
                SelectedGuid                                =   priceList.Values[0].pricelevelid;
            if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmHelper GetPriceListsByCurrency found Count: {0}, SelectedGuid: {1}",priceList.Count,SelectedGuid),CRMTraceSwitch.Sw.Info);
            return priceList;            
        }
        #endregion PriceList


    }
}
